const nodemailer = require('nodemailer');
const config = require('../config/index');

// 创建邮件发送器
const transporter = nodemailer.createTransport({
    host: config.EMAIL_HOST,
    port: config.EMAIL_PORT,
    secure: config.EMAIL_SECURE,
    auth: {
        user: config.EMAIL_USER,
        pass: config.EMAIL_PASS
    }
});

/**
 * 发送验证码邮件
 * @param {string} to 收件人邮箱
 * @param {string} code 验证码
 * @param {string} type 类型(register/update)
 * @returns {Promise<Object>} 发送结果
 */
async function sendVerificationEmail(to, code, type = 'register') {
    try {
        const subject = type === 'register' ? 'X聊天系统 - 注册验证码' : 'X聊天系统 - 邮箱修改验证码';
        const actionText = type === 'register' ? '注册' : '修改邮箱';

        const info = await transporter.sendMail({
            from: `"X聊天系统" <${config.EMAIL_USER}>`,
            to: to,
            subject: subject,
            html: `
        <div style="max-width: 600px; margin: 0 auto; padding: 20px; font-family: Arial, sans-serif;">
          <h2 style="color: #1890ff; text-align: center;">X聊天系统</h2>
          <p>您好，</p>
          <p>您正在进行${actionText}操作。请使用以下验证码完成验证：</p>
          <div style="background-color: #f5f5f5; padding: 15px; text-align: center; font-size: 24px; font-weight: bold; letter-spacing: 5px; margin: 20px 0;">
            ${code}
          </div>
          <p>验证码有效期为5分钟，请勿将验证码泄露给他人。</p>
          <p>如果您没有进行此操作，请忽略此邮件。</p>
          <p style="margin-top: 30px; color: #888; font-size: 12px;">此邮件由系统自动发送，请勿直接回复。</p>
        </div>
      `
        });

        return { success: true, messageId: info.messageId };
    } catch (error) {
        console.error("发送邮件失败:", error);
        return { success: false, error };
    }
}

module.exports = {
    sendVerificationEmail
};
